﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Collections.Generic;
using Infragistics.WebUI.UltraWebGrid;
using uMES.LeanManufacturing.Common;
using System.IO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.ParameterDTO;
using System.Text;
using System.Text.RegularExpressions;
using uMES.LeanManufacturing.DBUtility;
using System.Drawing;
using System.Data.OracleClient;
using Infragistics.WebUI.UltraWebNavigator;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class uMEPartReportingForm2 : System.Web.UI.Page
{
    const string QueryWhere = "uMEPartReporting";
    uMESCommonBusiness common = new uMESCommonBusiness();
    uMESPartReportingBusiness bll = new uMESPartReportingBusiness();
    uMESProductTreeViewBusiness productTreeBal = new uMESProductTreeViewBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    int m_PageSize = 9;

    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：零件进度表";
        master.strTitle = "零件进度表";
        master.ChangeFrame(true);
        NormalReportControl normalCntrl = new NormalReportControl();
        //normalCntrl.LtnFirst = lbtnFirst;
        //normalCntrl.LtnLast = lbtnLast;
        //normalCntrl.LtnNext = lbtnNext;
        //normalCntrl.LtnPrev = lbtnPrev;
        //normalCntrl.BtnReset = btnReSet;
        //normalCntrl.BtnGo = btnGo;
        //normalCntrl.BtnSearch = btnSearch;
        //normalCntrl.LabPages = lLabel1;
        //normalCntrl.TxtPage = txtPage;
        //normalCntrl.TxtTotalPage = txtTotalPage;
        //normalCntrl.TxtCurrentPage = txtCurrentPage;
        //normalCntrl.NormalOperation = this;
        //normalCntrl.QueryWhere = QueryWhere;
        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { QueryData(upageTurning.CurrentPageIndex); });
        getProductInfo.DDlProductDataChanged += new GetProductInfo_ascx.DDlProductDataChangedEventHandler(() => { ProductTreeSearch(); });
        if (!IsPostBack)
        {
            AddColumns();
            ClearMessage();
            getProductInfo.GetProductControlDiv.Style["width"] = "190px";
            getProductInfo.GetSearchBtn.Visible = false;
        }

        btnPrint.Enabled = false;
    }


    #region 重置
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ResetData();
    }

    void ResetData() {
        upageTurning.TxtCurrentPageIndex.Text = "1";
        ShowStatusMessage("", true);
        hdScanCon.Value = string.Empty;
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = "";
        txtEndDate.Value = "";
        txtSpecName.Text = string.Empty;
        wgResult.Rows.Clear();
        wgResult.Columns.Clear();
        upageTurning.TotalRowCount = 0;
        AddColumns();
        txtSrTreeProcessNo.Text = "";
        txtSrTreeProduct.Text = "";
    }
    #endregion
    public Dictionary<string, string> GetQuery()
    {
        string strScanContainerName = txtScan.Text.Trim();
        string strProcessNo = txtProcessNo.Text.Trim();
        string strContainerName = txtContainerName.Text.Trim();
        string strProductName = txtProductName.Text.Trim();
        string strStartDate = txtStartDate.Value.Trim();
        string strEndDate = txtEndDate.Value.Trim();
        string strSpecName = txtSpecName.Text.Trim();

        Dictionary<string, string> result = new Dictionary<string, string>();
        if (!string.IsNullOrEmpty(hdScanCon.Value))
        {
            result.Add("ScanContainerName", hdScanCon.Value);
        }
        else
        {
            result.Add("ProcessNo", strProcessNo);
            result.Add("ContainerName", strContainerName);
            result.Add("ProductName", strProductName);
            result.Add("StartDate", strStartDate);
            result.Add("EndDate", strEndDate);
            result.Add("SpecName", strSpecName);
        }
        return result;
    }

    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ShowStatusMessage("", true);

        try
        {
            upageTurning.TxtCurrentPageIndex.Text = "1";
            string strScan = txtScan.Text.Trim();
            txtScan.Text = "";
            hdScanCon.Value = string.Empty;
            if (strScan != string.Empty)
            {
                hdScanCon.Value = strScan;
                QueryData(1);
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public void QueryData(int intIndex)
    {
        try
        {
            ShowStatusMessage("", true);
            uMESPagingDataDTO result = bll.GetPartReportingMainInfo(GetQuery(), intIndex, m_PageSize);
            wgResult.Rows.Clear();
            wgResult.Columns.Clear();
            Drawing(result.DBset);
            //给分页控件赋值，用于分页控件信息显示
            this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
            this.upageTurning.RowCountByPage = m_PageSize;

        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
        }

    }

    /// <summary>
    /// 绘制零件进度表显示界面
    /// </summary>
    /// <param name="ds"></param>
    void Drawing(DataSet ds)
    {
        DataTable disDt = new DataTable();
        disDt.Columns.Add("Seqnumber");//序号
        disDt.Columns.Add("processno");//工作令号
        disDt.Columns.Add("oprno");//作业令号
        disDt.Columns.Add("productname");//图号
        disDt.Columns.Add("description");//名称
        disDt.Columns.Add("containername");//批次号
        disDt.Columns.Add("conqty");//批次数量
        disDt.Columns.Add("isSpec");//是否是工序
        disDt.Columns.Add("CurrentSpec");//当前工序工序
        disDt.Columns.Add("ProductID");
        disDt.Columns.Add("WorkflowID");
        disDt.Columns.Add("ContainerID");

        //创建Grid列
        AddColumns();

        //主信息
        DataTable dtMain = ds.Tables[0];

        //详细信息
        DataTable dt = ds.Tables[1];
        DataView dv = dt.DefaultView;
        dv.RowFilter = "isskiped = '' OR isskiped IS NULL";
        dv.Sort = "originalstartdate,ShowNo";
        DataTable dtDetail = dv.ToTable();

        //最大列值
        int maxColum = 0;

        if (dtDetail.Rows.Count > 0)
        {
            foreach (DataRow dr in dtMain.Rows)
            {
                string strFilter = String.Format("containername='{0}' ", dr["containername"].ToString().Trim());
                DataRow[] rows = dtDetail.Select(strFilter);
                if (maxColum < rows.Length)
                {
                    maxColum = rows.Length;
                }
            }
        }

        //创建工序列
        for (int i = 1; i <= maxColum; i++)
        {
            disDt.Columns.Add("A" + i.ToString().Trim());
        }

        //创建Grid工序列
        UltraGridColumn colum = new UltraGridColumn();
        for (int i = 1; i <= maxColum; i++)
        {
            colum = new UltraGridColumn("A" + i.ToString(), " ", ColumnType.NotSet, "");
            colum.BaseColumnName = "A" + i.ToString();
            colum.Key = "A" + i.ToString();
            colum.Width = 80;
            colum.HeaderStyle.Height = 20;
            colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
            wgResult.Bands[0].Columns.Add(colum);
        }

        //disDt赋值
        int rowindex = 0;
        int pageSize = m_PageSize;
        int pageIndex = upageTurning.CurrentPageIndex;
        //if (!string.IsNullOrEmpty(upageTurning.CurrentPageIndex.ToString))
        //{
        //    pageIndex = Convert.ToInt32(txtCurrentPage.Text);
        //}

        foreach (DataRow drMain in dtMain.Rows)
        {

            rowindex += 1;
            DataRow[] drInsrt;
            DataRow rowTmp = disDt.NewRow();
            rowTmp["Seqnumber"] = pageSize * (pageIndex - 1) + rowindex;
            rowTmp["processno"] = drMain["processno"];//工作令号
            rowTmp["oprno"] = drMain["oprno"];//作业令号
            rowTmp["productname"] = drMain["productname"];//图号
            rowTmp["description"] = drMain["description"];//名称
            rowTmp["containername"] = drMain["containername"];//批次号
            rowTmp["conqty"] = drMain["conqty"];//批次数量
            rowTmp["ProductID"] = drMain["ProductID"];
            rowTmp["WorkflowID"] = drMain["WorkflowID"];
            rowTmp["ContainerID"] = drMain["ContainerID"];
            //rowTmp["isSpec"] = "1";//批次数量


            disDt.Rows.Add(rowTmp);
            rowTmp = disDt.NewRow();
            rowTmp["Seqnumber"] = "";
            rowTmp["processno"] = "";//工作令号
            rowTmp["oprno"] = "";//作业令号
            rowTmp["productname"] = "";//图号
            rowTmp["description"] = "";//名称
            rowTmp["containername"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;正常";//批次号

            if (drMain["holdreasonid"].ToString() != "")
            {
                rowTmp["containername"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;暂停";
            }

            if (drMain["status"].ToString() == "2")
            {
                rowTmp["containername"] = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;关闭";
            }
            rowTmp["conqty"] = "";//批次数量
            rowTmp["ProductID"] = drMain["ProductID"];
            rowTmp["WorkflowID"] = drMain["WorkflowID"];
            //rowTmp["isSpec"] = "";
            disDt.Rows.Add(rowTmp);
            string strConName = drMain["containername"].ToString();
            string strConID = drMain["containerid"].ToString();
            drInsrt = dtDetail.Select("containername='" + strConName + "'", "showno,sequenceno");
            for (int h = 0; h < drInsrt.Length; h++)
            {
                string strWorkflowid = drInsrt[h]["workflowid"].ToString();
                string strSpecID = drInsrt[h]["specID"].ToString();
                string strSpecName = drInsrt[h]["specNameNew"].ToString();
                //工艺规程版本
                string strRevision =string.Empty;
                if (drInsrt[h]["workflowrevision"].ToString().Contains("LS"))
                {
                    strRevision = "临";
                }

                string strMainConId = string.Empty;
                if (!string.IsNullOrEmpty(drInsrt[h]["maincontainerid"].ToString()))
                {
                    strMainConId = drInsrt[h]["maincontainerid"].ToString();
                }

                string strUrl = "<a href='#' onclick =openSpecDetailwins('" + strConID + "','" + strSpecID + "','" + strWorkflowid + "')  style='font-size: small;height:10px;text-align: center;color:Blue;'>" + strSpecName + "</a>";

                if (strMainConId !="" && strMainConId!=null)
                {
                    strUrl = "<a href='#' onclick =openSpecDetailwins('" + strConID + "','" + strSpecID + "','" + strWorkflowid + "')  style='font-size: small;height:10px;text-align: center;color:Blue;'>" + strSpecName + "</a>";

                }
                //工序加工状态
                string strState = "-1";
                string strTmp = Color.Gainsboro.ToArgb().ToString()+","+strRevision;
                if (!string.IsNullOrEmpty(drInsrt[h]["state"].ToString()))
                {
                    strState = drInsrt[h]["state"].ToString();
                }
                switch (strState)
                {
                    case "1"://已派工
                        strTmp = Color.Yellow.ToArgb().ToString() + "," + strRevision; ;
                        break;
                    case "5"://已接收
                        strTmp = Color.Gold.ToArgb().ToString() + "," + strRevision; ;
                        break;
                    case "2"://已报工
                        strTmp = Color.YellowGreen.ToArgb().ToString() + "," + strRevision; ;
                        break;
                    case "3": //已检验
                        strTmp = Color.DeepSkyBlue.ToArgb().ToString() + "," + strRevision; ;
                        break;
                    case "4": //已完工
                        strTmp  = Color.Green.ToArgb().ToString() + "," + strRevision; ;
                        break;

                }
                //当前工序
                string strCurrentSpec = drInsrt[h]["iscurrentspec"].ToString();
                //是否有质量问题
                if (!string.IsNullOrEmpty(drInsrt[h]["IsQuality"].ToString()))
                {
                    strTmp = strTmp + ",1";
                }

                if (!string.IsNullOrEmpty(drInsrt[h]["synerspec"].ToString()))
                {
                    strTmp = strTmp + ",外协";
                }

                //是否协作工序

                if (disDt.Rows.Count > 2)
                {
                    if (strCurrentSpec == "1")
                    {
                        disDt.Rows[disDt.Rows.Count - 2]["CurrentSpec"] = strUrl + "A" + (h + 1).ToString();
                    }
                    disDt.Rows[disDt.Rows.Count - 2]["IsSpec"] = "1";
                    disDt.Rows[disDt.Rows.Count - 2]["A" + (h + 1).ToString()] = strUrl;
                }
                else
                {
                    if (strCurrentSpec == "1")
                    {
                        disDt.Rows[0]["CurrentSpec"] = strUrl + "A" + (h + 1).ToString();
                    }

                    disDt.Rows[0]["IsSpec"] = "1";
                    disDt.Rows[0]["A" + (h + 1).ToString()] = strUrl;
                }

                disDt.Rows[disDt.Rows.Count - 1]["A" + (h + 1).ToString()] = strTmp;

            }
        }
        wgResult.DataSource = disDt;
        wgResult.DataBind();

    }
    void DrawingOld(DataSet ds)
    {
        DataTable disDt = new DataTable();
        disDt.Columns.Add("Seqnumber");//序号
        disDt.Columns.Add("processno");//工作令号
        disDt.Columns.Add("oprno");//作业令号
        disDt.Columns.Add("productname");//图号
        disDt.Columns.Add("description");//名称
        disDt.Columns.Add("containername");//批次号
        disDt.Columns.Add("conqty");//批次数量
        disDt.Columns.Add("isSpec");//是否是工序
        disDt.Columns.Add("CurrentSpec");//当前工序工序


        //创建Grid列
        AddColumns();

        //主信息
        DataTable dtMain = ds.Tables[0];

        //详细信息
        DataTable dt = ds.Tables[1];
        DataView dv = dt.DefaultView;
        dv.Sort = "originalstartdate,ShowNo";
        DataTable dtDetail = dv.ToTable(true, "containerid", "containername", "workflowid", "ShowNo");

        //最大列值
        int maxColum = 0;

        if (dtDetail.Rows.Count > 0)
        {
            foreach (DataRow dr in dtDetail.Rows)
            {
                string strFilter = String.Format("containername='{0}' AND workflowid='{1}'", dr["containername"].ToString().Trim(), dr["workflowid"].ToString().Trim());
                DataRow[] rows = dt.Select(strFilter);
                if (maxColum < rows.Length)
                {
                    maxColum = rows.Length;
                }
            }

            //创建工序列
            for (int i = 1; i <= maxColum; i++)
            {
                disDt.Columns.Add("A" + i.ToString().Trim());
            }

            //创建Grid工序列
            UltraGridColumn colum = new UltraGridColumn();
            for (int i = 1; i <= maxColum; i++)
            {
                colum = new UltraGridColumn("A" + i.ToString(), " ", ColumnType.NotSet, "");
                colum.BaseColumnName = "A" + i.ToString();
                colum.Key = "A" + i.ToString();
                colum.Width = 80;
                colum.HeaderStyle.Height = 20;
                colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
                wgResult.Bands[0].Columns.Add(colum);
            }

            //disDt赋值
            int rowindex = 0;
            int pageSize = m_PageSize;
            int pageIndex = upageTurning.CurrentPageIndex;
            //if (!string.IsNullOrEmpty(txtCurrentPage.Text))
            //{
            //    pageIndex = Convert.ToInt32(txtCurrentPage.Text);
            //}

            foreach (DataRow drMain in dtMain.Rows)
            {

                rowindex += 1;
                DataRow[] drInsrt;
                DataRow rowTmp = disDt.NewRow();
                rowTmp["Seqnumber"] = pageSize * (pageIndex - 1) + rowindex;
                rowTmp["processno"] = drMain["processno"];//工作令号
                rowTmp["oprno"] = drMain["oprno"];//作业令号
                rowTmp["productname"] = drMain["productname"];//图号
                rowTmp["description"] = drMain["description"];//名称
                rowTmp["containername"] = drMain["containername"];//批次号
                rowTmp["conqty"] = drMain["conqty"];//批次数量
                //rowTmp["isSpec"] = "1";//批次数量

                string strConName = drMain["containername"].ToString();
                string strConID = drMain["containerid"].ToString();
                DataRow[] drDetail = dtDetail.Select("containername='" + strConName + "'");

                IList list = new List<string>();
                if (drDetail.Length > 0)
                {
                    for (int i = 0; i < drDetail.Length; i++)
                    {
                        string strWorkflowid = drDetail[i]["WORKFLOWID"].ToString().Trim();
                        string strShowNo = drDetail[i]["ShowNo"].ToString().Trim();
                        if (list.Contains(strWorkflowid + "," + strShowNo) == false)
                        {
                            list.Add(strWorkflowid + "," + strShowNo);
                        }
                    }

                    for (int l = 0; l < list.Count; l++)
                    {
                        string[] strWorkflowidList = list[l].ToString().Trim().Split(',');
                        string strWorkflowid = strWorkflowidList[0];
                        string strShowNo = strWorkflowidList[1];
                        string strFilterc = string.Format("containername='{0}' AND WORKFLOWID='{1}' AND ShowNo ='{2}'", strConName, strWorkflowid, strShowNo);
                        drInsrt = dt.Select(strFilterc, "SequenceNo");
                        if (l != 0)
                        {
                            rowTmp = disDt.NewRow();
                            rowTmp["Seqnumber"] = "";
                            rowTmp["processno"] = "";//工作令号
                            rowTmp["oprno"] = "";//作业令号
                            rowTmp["productname"] = "";//图号
                            rowTmp["description"] = "";//名称
                            rowTmp["containername"] = "";//批次号
                            rowTmp["conqty"] = "";//批次数量
                            //rowTmp["isSpec"] = "";

                        }
                        disDt.Rows.Add(rowTmp);

                        //工序加工进度颜色显示
                        rowTmp = disDt.NewRow();
                        rowTmp["Seqnumber"] = "";
                        rowTmp["processno"] = "";//工作令号
                        rowTmp["oprno"] = "";//作业令号
                        rowTmp["productname"] = "";//图号
                        rowTmp["description"] = "";//名称
                        rowTmp["containername"] = "";//批次号
                        rowTmp["conqty"] = "";//批次数量
                        //rowTmp["isSpec"] = "";
                        disDt.Rows.Add(rowTmp);
                        //工序列赋值
                        for (int h = 0; h < drInsrt.Length; h++)
                        {
                            string strSpecID = drInsrt[h]["specID"].ToString();
                            string strSpecName = drInsrt[h]["specNameNew"].ToString();
                            string strUrl = "<a href='#' onclick =openSpecDetailwins('" + strConID + "','" + strSpecID + "','" + strWorkflowid + "')  style='font-size: small;height:10px;text-align: center;color:Blue;'>" + strSpecName + "</a>";

                            //工序加工状态
                            string strState = "-1";
                            string strTmp = Color.Gainsboro.ToArgb().ToString();
                            if (!string.IsNullOrEmpty(drInsrt[h]["state"].ToString()))
                            {
                                strState = drInsrt[h]["state"].ToString();
                            }
                            switch (strState)
                            {
                                case "1"://已派工
                                    strTmp = Color.Yellow.ToArgb().ToString();
                                    break;
                                case "5"://已接收
                                    strTmp = Color.Gold.ToArgb().ToString();
                                    break;
                                case "2"://已报工
                                    strTmp = Color.YellowGreen.ToArgb().ToString();
                                    break;
                                case "3": //已检验
                                    strTmp = Color.DeepSkyBlue.ToArgb().ToString();
                                    break;
                                case "4": //已完工
                                    strTmp = strTmp = Color.Green.ToArgb().ToString();
                                    break;

                            }
                            //当前工序
                            string strCurrentSpec = drInsrt[h]["iscurrentspec"].ToString();
                            //是否有质量问题
                            if (!string.IsNullOrEmpty(drInsrt[h]["IsQuality"].ToString()))
                            {
                                strTmp = strTmp + ",1";
                            }
                            if (disDt.Rows.Count > 2)
                            {
                                if (strCurrentSpec == "1")
                                {
                                    disDt.Rows[disDt.Rows.Count - 2]["CurrentSpec"] = strUrl + "A" + (h + 1).ToString();
                                }
                                disDt.Rows[disDt.Rows.Count - 2]["IsSpec"] = "1";
                                disDt.Rows[disDt.Rows.Count - 2]["A" + (h + 1).ToString()] = strUrl;
                            }
                            else
                            {
                                if (strCurrentSpec == "1")
                                {
                                    disDt.Rows[0]["CurrentSpec"] = strUrl + "A" + (h + 1).ToString();
                                }

                                disDt.Rows[0]["IsSpec"] = "1";
                                disDt.Rows[0]["A" + (h + 1).ToString()] = strUrl;
                            }

                            disDt.Rows[disDt.Rows.Count - 1]["A" + (h + 1).ToString()] = strTmp;

                        }
                    }
                }
            }
        }
        wgResult.DataSource = disDt;
        wgResult.DataBind();

    }
    protected void wgResult_DataBound(object sender, EventArgs e)
    {
        {
            for (int i = 0; i < wgResult.Rows.Count; i++)
            {
                if (!string.IsNullOrEmpty(wgResult.Rows[i].Cells.FromKey("isspec").Text))
                {
                    if (wgResult.Rows[i].Cells.FromKey("isspec").Text == "1")
                    {
                        string strCSpecName = wgResult.Rows[i].Cells.FromKey("CurrentSpec").Text;
                        for (int j = 0; j < wgResult.Columns.Count; j++)
                        {
                            string strColName = wgResult.Columns[j].BaseColumnName.ToString();
                            if (wgResult.Columns[j].BaseColumnName.Contains("A"))
                            {
                                if (!string.IsNullOrEmpty(wgResult.Rows[i].Cells[j].Text))
                                {
                                    if ((wgResult.Rows[i].Cells[j].Text + strColName) == strCSpecName)
                                    {
                                        wgResult.Rows[i].Cells[j].Style.BackColor = Color.Pink;
                                    }

                                }
                            }
                        }
                        continue;
                    }
                }

                for (int j = 0; j < wgResult.Columns.Count; j++)
                {
                    if (wgResult.Columns[j].BaseColumnName.Contains("A"))
                    {
                        if (!string.IsNullOrEmpty(wgResult.Rows[i].Cells[j].Text))
                        {
                            string strTmp = wgResult.Rows[i].Cells[j].Text;
                            string[] strArray = wgResult.Rows[i].Cells[j].Text.Split(',');
                            if (strArray.Length >= 3)
                            {
                                wgResult.Rows[i].Cells[j].Style.BackColor = Color.FromArgb(Convert.ToInt32(strArray[0]));
                                if (strArray[strArray.Length - 1].ToString() == "1")
                                {
                                    wgResult.Rows[i].Cells[j].Text = strArray[1].ToString() + "&nbsp;&nbsp;&nbsp;▲";
                                }
                                else
                                {
                                    wgResult.Rows[i].Cells[j].Text = strArray[1].ToString() + "&nbsp;&nbsp;&nbsp;外协";
                                }
                               
                            }
                            else
                            {
                                wgResult.Rows[i].Cells[j].Style.BackColor = Color.FromArgb(Convert.ToInt32(strArray[0]));
                                wgResult.Rows[i].Cells[j].Text = "&nbsp;&nbsp;&nbsp;"+ strArray[strArray.Length - 1].ToString();
                            }
                        }
                    }
                }
            }
        }
    }
    /// <summary>
    /// 创建Grid列
    /// </summary>
    void AddColumns()
    {

        UltraGridColumn colum = new UltraGridColumn("xuhao", "序号", ColumnType.NotSet, "");
        colum.BaseColumnName = "Seqnumber";
        colum.Key = "Seqnumber";
        colum.Width = 40;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("processno", "工作令号", ColumnType.NotSet, "");
        colum.BaseColumnName = "processno";
        colum.Key = "processno";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("oprno", "作业令号", ColumnType.NotSet, "");
        colum.BaseColumnName = "oprno";
        colum.Key = "oprno";
        colum.Width = 120;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("productname", "图号", ColumnType.NotSet, "");
        colum.BaseColumnName = "productname";
        colum.Key = "productname";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("description", "名称", ColumnType.NotSet, "");
        colum.BaseColumnName = "description";
        colum.Key = "description";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("containername", "批次号", ColumnType.NotSet, "");
        colum.BaseColumnName = "containername";
        colum.Key = "containername";
        colum.Width = 120;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("conqty", "数量", ColumnType.NotSet, "");
        colum.BaseColumnName = "conqty";
        colum.Key = "conqty";
        colum.Width = 60;
        colum.Hidden = false;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("IsSpec", "IsSpec", ColumnType.NotSet, "");
        colum.BaseColumnName = "IsSpec";
        colum.Key = "IsSpec";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("CurrentSpec", "CurrentSpec", ColumnType.NotSet, "");
        colum.BaseColumnName = "CurrentSpec";
        colum.Key = "CurrentSpec";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("WorkflowID", "WorkflowID", ColumnType.NotSet, "");
        colum.BaseColumnName = "WorkflowID";
        colum.Key = "WorkflowID";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("ProductID", "ProductID", ColumnType.NotSet, "");
        colum.BaseColumnName = "ProductID";
        colum.Key = "ProductID";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

        colum = new UltraGridColumn("ContainerID", "ContainerID", ColumnType.NotSet, "");
        colum.BaseColumnName = "ContainerID";
        colum.Key = "ContainerID";
        colum.Width = 60;
        colum.Hidden = true;
        colum.HeaderStyle.Height = 20;
        colum.HeaderStyle.HorizontalAlign = HorizontalAlign.Center;
        colum.Header.Fixed = true;
        wgResult.Bands[0].Columns.Add(colum);

    }
    public void ResetQuery()
    {
        ShowStatusMessage("", true);

        Session[QueryWhere] = "";
        txtScan.Text = string.Empty;
        txtProcessNo.Text = string.Empty;
        txtContainerName.Text = string.Empty;
        txtProductName.Text = string.Empty;
        txtStartDate.Value = string.Empty;
        txtEndDate.Value = string.Empty;
        txtSpecName.Text = string.Empty;
        wgResult.Rows.Clear();
        upageTurning.TotalRowCount = 0;
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        // ClientScript.RegisterStartupScript(GetType(), "", strScript);
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }
    #endregion

    #region 清除提示信息
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"" + "" + "\", 'true');</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        try
        {
            try
            {
                upageTurning.Enabled();
                upageTurning.TxtCurrentPageIndex.Text = "1";
                hdScanCon.Value = string.Empty;
                QueryData(upageTurning.CurrentPageIndex);

            }
            catch (Exception ex)
            {
                ShowStatusMessage(ex.Message, false);
            }
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();

            UltraGridRow uldr = wgResult.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }

            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");poupDt.Columns.Add("ContainerID"); poupDt.Columns.Add("ContainerName");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("containername").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);

            //string strScript = string.Empty;
            //strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);

            var page = "../bwCommonPage/uMESDocumentViewPopupForm.aspx";
            var script = String.Format("<script>OpenPopupWindow(false,'{0}','dialogWidth={1}px;dialogHeight={2}px;status=0');</script>", page, 700, 600);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }


    #region 树形区域 add:Wangjh 20201020


    /// <summary>
    /// 遍历所有子节点，并查询订单
    /// </summary>
    /// <param name="childNodes"></param>
    /// <param name="dt"></param>
    void GetChildNodesData2(Nodes childNodes, DataSet ds)
    {

        foreach (Node node in childNodes)
        {
            string strContainerID = GetContaienrID(node);
            DataSet tempDs = QueryData3(node.Tag.ToString(),strContainerID);

            ds.Tables["containerName"].Merge(tempDs.Tables["containerName"]);
            ds.Tables["detailinfo"].Merge(tempDs.Tables["detailinfo"]);

            GetChildNodesData2(node.Nodes, ds);
        }
    }

    /// <summary>
    /// 查询该产品及其以下所有
    /// </summary>
    void SearchAllData2()
    {
        wgResult.Rows.Clear();
        wgResult.Columns.Clear();

        var selectNode = treeProduct.SelectedNode;
        if (selectNode == null)
        {
            ShowStatusMessage("请先选择节点", false);
            return;
        }
        // selectNode.nod
        string strContainerID = GetContaienrID(selectNode);
        DataSet ds = QueryData3(selectNode.Tag.ToString(), strContainerID);
        GetChildNodesData2(selectNode.Nodes, ds);

        //处理detail，去重，公共件情况
        var temdt = ds.Tables[1].DefaultView.ToTable(true);
        temdt.TableName = ds.Tables[1].TableName;
        ds.Tables[1].Clear();
        ds.Tables[1].Merge(temdt);

        Drawing(ds);

        DataTable dtPrint = ds.Tables[0].Copy();
        DataView dv = dtPrint.DefaultView;
        dv.RowFilter = "status <> 2";
        Session["DTPRINT"] = dv.ToTable();
    }

    protected void btnSearchAll_Click(object sender, EventArgs e)
    {
        try
        {
            upageTurning.Disabled();
            SearchAllData2();
            btnPrint.Enabled = true;
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    public void QueryData2(string productID, string strContainerID)
    {
        try
        {
            // Dictionary<string, string> para = GetQuery();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            para["ProductID"] = productID;

            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }
            if (!string.IsNullOrWhiteSpace(strContainerID))
            {
                para["ContainerIDList"] = strContainerID;
            }
            uMESPagingDataDTO result = bll.GetPartReportingMainInfo(para, 1, 100000);
            wgResult.Rows.Clear();
            wgResult.Columns.Clear();

            Drawing(result.DBset);

        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
        }

    }

    public DataSet QueryData3(string productID,string strContainerID)
    {
        try
        {
            // Dictionary<string, string> para = GetQuery();
            DataSet re = new DataSet();

            Dictionary<string, string> para = new Dictionary<string, string>();
            para["PageSize"] = m_PageSize.ToString();
            para["ProductID"] = productID;

            if (!string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
            {
                para["ProcessNo"] = txtTreeProcessNo.Text;
            }
            if (!string.IsNullOrWhiteSpace(strContainerID))
            {
                para["ContainerIDList"] = strContainerID;
            }

            uMESPagingDataDTO result = bll.GetPartReportingMainInfo(para, 1, 100000);
            re = result.DBset;

            return re;
        }
        catch (Exception e)
        {
            ShowStatusMessage(e.Message, false);
            return null;
        }

    }


    protected void treeProduct_NodeSelectionChanged(object sender, WebTreeNodeEventArgs e)
    {
        try
        {
            upageTurning.Disabled();
            ResetData();
            selectProductNode();

        }
        catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    void selectProductNode()
    {
        // var selectNode = tvTree.SelectedNode;
        // string productID = selectNode.Value;

        var selectNode = treeProduct.SelectedNode;
        string productID = selectNode.Tag.ToString();

        txtSrTreeProduct.Text = selectNode.Text;
        txtSrTreeProcessNo.Text = txtTreeProcessNo.Text;
        string strContainerID = GetContaienrID(selectNode);
        QueryData2(productID,strContainerID);
    }
    protected string GetContaienrID(Node selectNode)
    {
        string strContaienrID = "";
        string productID = selectNode.Tag.ToString();
        //获取父节点ProductID
        string parentProductID = "";
        if (selectNode.Parent != null)
        {
        parentProductID= selectNode.Parent.Tag.ToString();
        }
        if (Session["ProductTree"] == null)
        {
            string productName = "", productRev = "";
            GetProductInfo(ref productName, ref productRev);
            Dictionary<string, string> para = new Dictionary<string, string>();
            para.Add("ProductName", productName); para.Add("ProductRev", productRev);
            para.Add("ProcessNo", txtTreeProcessNo.Text);//工作令号
            Session["ProductTree"] = productTreeBal.GetSubProductInfo(para);
        }
   
        DataRow[] drProduct = ((DataTable)Session["ProductTree"]).Select("subproductid='" + productID + "'", "productid DESC");
        //获取公共件关联的批次信息
        DataRow[] drContainer = ((DataTable)Session["ProductContainer"]).Select("productid='" + productID + "'", "mfgorderid,containerid");
        //判断当前选中节点中是否公共件
        if (drProduct.Length > 1 && drContainer.Length>0)
        {
            if (drProduct.Length <= drContainer.Length)
            {
                //公共件的个数小于等于批次个数
                int intIndex = -1;
                for (int i = 0; i < drProduct.Length; i++)
                {
                    if (drProduct[i]["productid"].ToString() == parentProductID)
                    {
                        intIndex = i;
                        strContaienrID += "'" + drContainer[intIndex]["containerid"] + "',";
                        //判断是否是最后一个组件如果是则将剩余的批次关联至该组件上
                        if (i==drProduct.Length-1)
                        {
                            for (int j=intIndex+1;j<drContainer.Length;j++)
                            {
                                strContaienrID += "'" + drContainer[j]["containerid"] + "',";
                            }
                        }
                        break;
                    }

                }
                   
            }
            else
            {
                if (drContainer.Length == 1)
                {
                    //只有一个批次时，批次数量大于组件个数则每个组件都可以看到批次信息
                    if (int.Parse(drContainer[0]["qty"].ToString()) >= drProduct.Length)
                    {
                        strContaienrID += "'" + drContainer[0]["containerid"] + "',";
                    }
                    else
                    {
                        for (int i = 0; i < drProduct.Length; i++)
                        {
                            if (drProduct[i]["productid"].ToString() == parentProductID)
                            {
                                if (i + 1 <= int.Parse(drContainer[0]["qty"].ToString()))
                                {
                                    strContaienrID += "'" + drContainer[0]["containerid"] + "',";
                                }
                            }
                        }
                    }

                }
                else
                {
                    for (int i = 0; i < drProduct.Length; i++)
                    {
                        if (drProduct[i]["productid"].ToString() == parentProductID)
                        {
                            if (i < drProduct.Length)
                            {
                                strContaienrID += "'" + drContainer[0]["containerid"] + "',";
                            }
                        }
                    }
                }
            }
        }
        if (strContaienrID != "")
        {
            strContaienrID = strContaienrID.TrimEnd(',');
        }
        return strContaienrID;
    }
   

    protected void btnTreeSearch_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try {
            TreeSearchProduct();
            // ProductTreeSearch();
        } catch (Exception ex) { ShowStatusMessage(ex.Message, false); }

    }

    //获取产品名及版本
    void GetProductInfo(ref string productName, ref string productRev)
    {
        string productInfo = getProductInfo.ProducText;

        if (productInfo == "")
        {
            return;
        }

        productName = productInfo.Substring(0, productInfo.IndexOf(":"));
        productRev = productInfo.Substring(productInfo.IndexOf(":") + 1, productInfo.IndexOf("(", productName.Length) - productInfo.IndexOf(":") - 1);

    }

    //UltraWebTree
    Node GetProductTree2(string productName, string productRev, DataTable dt)
    {
        Node productTree = new Node();

        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));


        for (int i = 0; i < drs.Length; i++)
        {
            Node productSubTree = GetProductTree2(drs[i]["subproductname"].ToString(), drs[i]["subproductrev"].ToString(), dt);

            productSubTree.Text = drs[i]["subproductname"].ToString();// + ":" + drs[i]["subproductrev"].ToString(); //+ " | " + drs[i]["subproductstatus"].ToString();
            productSubTree.Tag = drs[i]["subproductid"].ToString();
            productTree.Nodes.Add(productSubTree);
        }

        return productTree;

    }


    /// <summary>
    /// 产品结构树
    /// </summary>
    void ProductTreeSearch()
    {
        treeProduct.Nodes.Clear();       
        hdProductID.Value = "";//
        Session["ProductMfgorder"] = null;
        Session["ProductTree"] = null;
        Session["ProductContainer"] = null;
        string productName = "", productRev = "";
        GetProductInfo(ref productName, ref productRev);
        if (string.IsNullOrWhiteSpace(productName))
        {
            ShowStatusMessage("请选择产品", false);
            return;
        }
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para.Add("ProductName", productName); para.Add("ProductRev", productRev);
        para.Add("ProcessNo", txtTreeProcessNo.Text);//工作令号
        DataTable dt = productTreeBal.GetSubProductInfo(para);

        if (dt.Rows.Count == 0)
        {
            ShowStatusMessage("此产品没有子级零组件", false);
            return;
        }
        Session["ProductTree"] = dt;
        //将结构树中所有零组件的ID赋值 hdProductID 控件
        foreach (DataRow dr in dt.Rows)
        {
            if (hdProductID.Value.Contains("'"+dr["productid"] +"',")==false)
            {
                hdProductID.Value += "'" + dr["productid"] + "',";
            }
            if (hdProductID.Value.Contains("'" + dr["subproductid"] + "',") == false)
            {
                hdProductID.Value += "'" + dr["subproductid"] + "',";
            }
        }
        //获取树形结构中产品关联的订单信息
        if (hdProductID.Value !="")
        {
            Session["ProductMfgorder"] = productTreeBal.GetMfgorderInfo(hdProductID.Value.TrimEnd(','), txtTreeProcessNo.Text);
            Session["ProductContainer"] = productTreeBal.GetContainerInfo(hdProductID.Value.TrimEnd(','), txtTreeProcessNo.Text);
        }
        //TreeView
        /*
        TreeNode productTree = GetProductTree(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString() + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Value = drs[0]["productid"].ToString();
        tvTree.Nodes.Add(productTree);
        tvTree.Nodes[0].Expand();
        */
        //UltraWebTree
        Node productTree = GetProductTree2(productName, productRev, dt);
        DataRow[] drs = dt.Select(string.Format("productname='{0}' and productrev='{1}'", productName, productRev));
        productTree.Text = drs[0]["productname"].ToString();// + ":" + drs[0]["productrev"].ToString(); //+ " | " + drs[0]["productStatus"].ToString();
        productTree.Tag = drs[0]["productid"].ToString();
        treeProduct.Nodes.Add(productTree);
        treeProduct.Nodes[0].Expand(false);
    }

    

    protected void btnTreeReset_Click(object sender, EventArgs e)
    {
        try
        {
            ResetData();
            txtTreeProcessNo.Text = string.Empty;
            getProductInfo.InitControl();
            treeProduct.Nodes.Clear();
            hdProductID.Value = "";
            Session["ProductMfgorder"] = null;
            Session["ProductContainer"] = null;
            Session["ProductTree"] = null;
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

    /// <summary>
    /// 根据工作令号查询产品
    /// </summary>
    void TreeSearchProduct()
    {
        treeProduct.Nodes.Clear();
        hdProductID.Value = "";
        Session["ProductMfgorder"] = null;
        Session["ProductTree"] = null;
        Session["ProductContainer"] = null;
        if (string.IsNullOrWhiteSpace(txtTreeProcessNo.Text))
        {
            ShowStatusMessage("请选择工作令号", false);
            return;
        }
        DataTable dt = containerBal.GetProductByProcess(txtTreeProcessNo.Text);
        getProductInfo.GetProductDDL.Visible = true;
        getProductInfo.GetProductNameOrTypeText.Visible = false;

        getProductInfo.GetProductDDL.DataTextField = "PRODUCTNAME";
        getProductInfo.GetProductDDL.DataValueField = "PRODUCTID";
        getProductInfo.GetProductDDL.DataSource = dt;
        getProductInfo.GetProductDDL.DataBind();

        getProductInfo.GetProductDDL.Items.Insert(0, "");
    }
    #endregion

    //打印任务表格
    protected void btnPrint_Click(object sender, EventArgs e)
    {
        ClearMessage();

        try
        {
            DataTable dtPrint = (DataTable)Session["DTPRINT"];
            if (dtPrint == null)
            {
                ShowStatusMessage("没有数据供打印", false);
                return;
            }

            if (dtPrint.Rows.Count <= 0)
            {
                ShowStatusMessage("没有数据供打印", false);
                return;
            }

            var page = "PrintTaskTableForm.aspx";
            var script = String.Format("<script>window.open('{0}');</script>", page);
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, script);

            btnPrint.Enabled = true;
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }

}